package com.sfh.cp.mass.pst.impl;

import com.sfh.cp.mass.pst.IPstMassAddMessage;
import com.sfh.cp.mass.req.ReqAddMessage;
import com.sfh.cp.mass.req.RxNoteMessageSize;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.RxBusEventManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import crm.sfh.server.Const;
import crm.sfh.server.MangeNote;
import crm.sfh.server.MangerUser;
import crm.sfh.server.SMessage;
import crm.sfh.server.SNote;
import crm.sfh.server.SUser;

/**
 * 功能描述:
 *
 * @date 2018/5/2
 */
public class PstMassAddMessage extends AbstractPresenter<IPstMassAddMessage.IVAddMessage> implements IPstMassAddMessage{

    @Override
    public void addMessage(final ReqAddMessage req) {
        getView ().showLoading (true);
        SUser user = AppCacheManager.newInstance().getCache(Const.USER, new SUser());
        final SMessage message = new SMessage ();
        message.setAuthor (user);
        message.setContent (req.getContent ());
        message.setNoteId (req.getNoteId ());
        message.setSizeFabulous (0L);

        message.save (AppCacheManager.getApplication (), new SaveListener () {

            @Override
            public void onSuccess() {

                RxBusEventManager.postEvent(new RxNoteMessageSize(req.getNoteId ()));
                getView ().hideLoading ();
                updateSize(message);
                getView ().showToast ("评论成功");
                getView ().onSuccess ();
            }

            @Override
            public void onFailure(int i, String s) {
                getView ().hideLoading ();
                getView ().showToast ("评论失败");
            }
        });

    }

    private void updateSize(final SMessage message){

        BmobQuery<SNote> query = new BmobQuery<> ();
        query.include("author");
        query.getObject (AppCacheManager.getApplication (), message.getNoteId(), new GetListener<SNote> () {

            @Override
            public void onSuccess(SNote sNote) {
                //消息数量+1
                sNote.increment("sizeMessage");
                if (sNote.getFristMsg() == null){
                    sNote.setFristMsg(message);
                }else if (sNote.getTwoMsg() == null){
                    sNote.setTwoMsg(message);
                }else if (sNote.getThreeMsg() == null){
                    sNote.setThreeMsg(message);
                }
                sNote.update (AppCacheManager.getApplication ());

                // 魅力+5
                new MangerUser().updateCharm(AppCacheManager.getApplication(),sNote.getAuthor().getObjectId(),5,null);

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });

    }




}
